import { loginRequest } from '@/api/login'
import { getUserRoleRequest } from '@/api/right'
import { dynamicRoutes } from '@/router'
import routesPermit from '@/utils/routesPermit'
import * as storage from '@/utils/app.js'
const state = {
  token: storage.getTokenStorage || '',
  username: storage.getUsernameStorage || '',
  system: [],
  button: [],
  addRoutes: []
}
const mutations = {
  setToken (state, data) {
    state.token = data
    storage.setTokenStorage(data)
  },
  setUsername (state, data) {
    state.username = data
    storage.setUsernameStorage(data)
  },
  setSystem (state, data) {
    state.system = data
  },
  setButton (state, data) {
    state.button = data
  },
  setAddRoutes (state, data) {
    state.addRoutes = data
  },
  removeToken (state) {
    state.token = ''
  },
  removeUsername (state) {
    state.username = ''
  },
  removeSystem (state) {
    state.system = []
  }
}
const actions = {
  async login (content, data) {
    const { data: res } = await loginRequest(data).catch(err => err)
    content.commit('setToken', res.data.token)
    content.commit('setUsername', res.data.username)
    return res
  },
  logout (content) {
    return new Promise((resolve, reject) => {
      content.commit('removeToken')
      content.commit('removeUsername')
      resolve()
    })
  },
  async getSystem (content) {
    const { data: res } = await getUserRoleRequest()
    content.commit('setSystem', res.data.role)
    content.commit('setButton', res.data.button)
  },
  createRoutes (content) {
    let addRoutes
    const routes = JSON.parse(JSON.stringify(dynamicRoutes))
    if (content.state.system.includes('admin')) {
      addRoutes = dynamicRoutes
    } else {
      addRoutes = routesPermit(content.state.system, routes)
      console.log(addRoutes)
    }
    console.log(addRoutes)
    content.commit('setAddRoutes', addRoutes)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
